<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-card>
      <el-form :model="queryParams" ref="queryForm" :inline="false" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="入库状态" prop="orderStatus">
              <el-radio-group v-model="queryParams.orderStatus" @change="handleQuery">
                <el-radio-button  label="all">
                  全部
                </el-radio-button>
                <el-radio-button v-for="item in putawayFilterStatus" :key="item.value" :label="item.value">
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="billsId">
              <el-input v-model="queryParams.billsId" placeholder="请输入入库单号" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="供应商" prop="supplierName">-->
          <!--              <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable-->
          <!--                @keyup.enter.native="handleQuery" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="dateRange">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                              end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="handleDateChange"
                              style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 业务流程说明 -->
    <el-card class="mt20">
      <el-alert title="上架管理说明" type="info" :closable="false" class="mb8">
        <template #default>
          <div style="font-size: 13px; line-height: 22px;">
            <p>📋 <strong>上架流程：</strong>从验收完成的单据中查询待上架的单据 → 执行上架（选择货位、确认上架） → 上架完成
            </p>
            <p>📊 <strong>数据来源：</strong>上架任务来自入库主表中状态为2（已验收待上架）的单据</p>
            <p>✅ <strong>上架完成：</strong>状态更新为「已上架」（状态3），记录上架人员、时间</p>
            <p>📱 <strong>PDA操作：</strong>PDA上架完成后会直接修改数据库状态，系统同步显示最新状态</p>
            <p>🔢 <strong>状态说明：</strong>0-未收货，1-已收货待验收，2-已验收待上架，3-已上架，4-异常，5-作废</p>
          </div>
        </template>
      </el-alert>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="mb8">
        <el-col :span="6">
          <el-card class="stat-card" @click.native="handleStatClick('')">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.totalTasks }}</div>
              <div class="stat-label">总任务数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" @click.native="handleStatClick('2')">
            <div class="stat-item">
              <div class="stat-value pending">{{ statistics.pendingTasks }}</div>
              <div class="stat-label">待上架</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" @click.native="handleStatClick('3')">
            <div class="stat-item">
              <div class="stat-value completed">{{ statistics.completedTasks }}</div>
              <div class="stat-label">已完成</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" @click.native="handleStatClick('4')">
            <div class="stat-item">
              <div class="stat-value exception">{{ statistics.exceptionTasks }}</div>
              <div class="stat-label">异常</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="handleBatchPutaway"
                     :disabled="multiple" v-hasPermi="['wms:putaway:edit']">批量上架
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                     v-hasPermi="['wms:putaway:export']">导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-refresh" size="mini" @click="handleRefresh">刷新</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="taskList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="入库单号" align="center" prop="billsId" width="200" show-overflow-tooltip
                         sortable="custom"/>
        <el-table-column label="供应商" align="center" prop="billsCdName" show-overflow-tooltip/>
        <el-table-column label="状态" align="center" prop="billsState" width="150">
          <template slot-scope="scope">
            <el-tag :type="getBillsStateTag(scope.row.billsState)" size="small">
              {{ getBillsStateText(scope.row.billsState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上架人" align="center" prop="shelvingUserName" width="160" sortable="custom"/>
        <el-table-column label="上架时间" align="center" prop="shelvingTime" width="160" sortable="custom"/>
        <el-table-column label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
                       v-hasPermi="['wms:putaway:query']">详情
            </el-button>
            <el-button v-if="scope.row.billsState === '2'" size="mini" type="text" icon="el-icon-upload2"
                       @click="handlePutaway(scope.row)" style="color: #67C23A;"
                       v-hasPermi="['wms:putaway:edit']">上架
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详情对话框 -->
    <el-dialog title="上架任务详情" :visible.sync="detailOpen" width="1000px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="入库单号">{{ detail.task.billsId }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ detail.task.billsCdName }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getBillsStateTag(detail.task.billsState)" size="small">
            {{ getBillsStateText(detail.task.billsState) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="上架人">{{ detail.task.shelvingUserName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="上架时间">{{ detail.task.shelvingTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detail.task.createBy || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ detail.task.createTime }}</el-descriptions-item>
        <el-descriptions-item v-if="detail.task.remark" label="备注" :span="2">{{ detail.task.remark }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">商品明细</el-divider>
      <el-table :data="detail.detailList" border stripe v-if="detail.detailList && detail.detailList.length > 0" max-height="400">
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column label="商品编码" align="center" prop="drugId" width="120" show-overflow-tooltip/>
        <el-table-column label="商品名称" align="center" prop="drugName" min-width="150" show-overflow-tooltip/>
        <el-table-column label="规格" align="center" prop="drugGg" width="80" show-overflow-tooltip/>
        <el-table-column label="单位" align="center" prop="drugDw" width="80"/>
        <el-table-column label="数量" align="center" prop="drugNum" width="100"/>
        <el-table-column label="确认数量" align="center" prop="drugCheckNum" width="100"/>
        <el-table-column label="批号" align="center" prop="drugBatchNo" width="120" show-overflow-tooltip/>
        <el-table-column label="生产日期" align="center" prop="drugPd" width="120"/>
        <el-table-column label="有效期" align="center" prop="drugExp" width="120"/>
        <el-table-column label="货位" align="center" prop="huoWei" width="100" show-overflow-tooltip/>
      </el-table>
      <el-empty v-else description="暂无商品明细" :image-size="100"></el-empty>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listPutawayTask, completeTask} from '@/api/wms/putaway'

export default {
  name: 'PutawayTask',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 上架任务表格数据
      taskList: [],
      // 日期范围
      dateRange: [],
      // 是否显示详情弹出层
      detailOpen: false,
      // 详情数据
      detail: {
        task: {},
        detailList: []
      },
      // 统计数据
      statistics: {
        totalTasks: 0,
        pendingTasks: 0,
        processingTasks: 0,
        completedTasks: 0,
        exceptionTasks: 0
      },
      // 入库状态定义（完整状态映射）
      // 0-未收货，1-已收货待验收，2-已验收待上架，3-已上架，4-异常，5-作废
      wms_receipt_status: [
        { label: '未收货', value: '0' },
        { label: '已收货待验收', value: '1' },
        { label: '已验收待上架', value: '2' },
        { label: '已上架', value: '3' },
        { label: '异常', value: '4' },
        { label: '作废', value: '5' }
      ],
      // 上架管理筛选状态（只显示上架相关状态）
      putawayFilterStatus: [
        { label: '待上架', value: '2' },
        { label: '已上架', value: '3' },
        { label: '异常', value: '4' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billsId: null,
        productName: null,
        orderStatus: "all",
        beginTime: null,
        optType: -1,//收货
        endTime: null,
        orderByColumn: null,
        isAsc: null
      }
    }
  },
  created() {
    this.getList()
    this.getGlobalStatistics()
  },
  methods: {
    /** 查询上架任务列表 */
    getList() {
      this.loading = true
      this.queryParams.type = '2';
      listPutawayTask(this.queryParams).then(response => {
        this.taskList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /** 获取全局统计数据（根据主表billsState统计） */
    getGlobalStatistics() {
      // 获取所有数据，在前端根据 billsState 统计
      const params = {
        pageNum: 1,
        pageSize: 999999, // 获取所有数据
        optType: -1,
        type: '2',
        orderStatus: 'all'
      }

      listPutawayTask(params).then(response => {
        const data = response.rows || []

        // 根据主表 billsState 字段统计各状态数量
        this.statistics.totalTasks = data.length
        this.statistics.pendingTasks = data.filter(item => item.billsState === '2').length
        this.statistics.completedTasks = data.filter(item => item.billsState === '3').length
        this.statistics.exceptionTasks = data.filter(item => item.billsState === '4').length
      }).catch(error => {
        console.error('获取统计数据失败:', error)
      })
    },

    /** 处理统计卡片点击 */
    handleStatClick(status) {
      this.queryParams.orderStatus = status || 'all'
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 刷新 */
    handleRefresh() {
      this.getList()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.dateRange = []
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
      this.handleQuery()
    },

    /** 日期范围变化 */
    handleDateChange(dates) {
      if (dates && dates.length === 2) {
        this.queryParams.beginTime = dates[0]
        this.queryParams.endTime = dates[1]
      } else {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      }
    },

    /** 排序变化 */
    handleSortChange({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc'
      this.getList()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 查看详情 */
    handleDetail(row) {
      // 直接使用当前行数据填充详情对话框
      this.detail.task = {
        billsId: row.billsId,
        billsCdName: row.billsCdName,
        billsState: row.billsState,
        shelvingUserName: row.shelvingUserName,
        shelvingTime: row.shelvingTime,
        createTime: row.createTime,
        createBy: row.createBy,
        remark: row.remark
      }
      this.detail.detailList = row.inDetailList || []
      this.detailOpen = true
    },

    /** 上架操作 */
    handlePutaway(row) {
      this.$confirm('确认完成入库单据"' + row.billsId + '"的上架操作？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 传递单据ID和明细列表
        return completeTask(row.billsId, row.inDetailList || [])
      }).then(() => {
        this.$message.success('上架成功')
        this.getList()
        this.getGlobalStatistics()
      }).catch(() => {
      })
    },

    /** 批量上架 */
    handleBatchPutaway() {
      if (!this.ids.length) {
        this.$message.warning('请选择要上架的任务')
        return
      }

      const pendingTasks = this.taskList.filter(item =>
        this.ids.includes(item.id) && item.billsState === '2'
      )

      if (!pendingTasks.length) {
        this.$message.warning('所选任务中没有可上架的任务')
        return
      }

      this.$confirm('确认批量上架选中的 ' + pendingTasks.length + ' 个任务？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 批量上架，传递每个任务的单据ID和明细列表
        const promises = pendingTasks.map(item => completeTask(item.billsId, item.inDetailList || []))
        return Promise.all(promises)
      }).then(() => {
        this.$message.success('批量上架成功')
        this.getList()
        this.getGlobalStatistics()
      }).catch(() => {
      })
    },

    /** 导出 */
    handleExport() {
      this.$confirm('确认导出所有上架任务数据?', '提示', {type: 'warning'}).then(() => {
        this.$message.success('导出功能开发中...')
      })
    },

    /** 获取单据状态标签类型 */
    getBillsStateTag(state) {
      const mapping = {
        '0': 'info',      // 未收货
        '1': 'warning',   // 已收货待验收
        '2': 'success',   // 已验收待上架
        '3': 'success',   // 已上架
        '4': 'danger',    // 异常
        '5': 'info'       // 作废
      }
      return mapping[state] || 'info'
    },

    /** 获取单据状态文本 */
    getBillsStateText(state) {
      const item = this.wms_receipt_status.find(s => s.value === state)
      return item ? item.label : state
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.stat-value.exception {
  color: #F56C6C;
}

.mt20 {
  margin-top: 20px;
}

.stat-card {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-item {
  padding: 10px 0;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-value.pending {
  color: #909399;
}

.stat-value.processing {
  color: #E6A23C;
}

.stat-value.completed {
  color: #67C23A;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.product-info {
  line-height: 1.6;
}

.product-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 2px;
}

.product-spec {
  font-size: 12px;
  color: #909399;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
